#include "../source/server.hpp"

void HandleClose(Channel* channel)
{
    std::cout << "close: " << channel->Fd() << std::endl;
    LOG(DEBUG, "close fd: %d", channel->Fd());
    channel->Remove(); // 移出监控
    delete channel;
}

void HandleRead(Channel* channel)
{
    int fd = channel->Fd();
    char buff[1024] = { 0 };
    int ret = recv(fd, buff, 1023, 0);
    if(ret <= 0)
        return HandleClose(channel); //关闭释放
    LOG(DEBUG, "%s", buff);
    channel->EnableWrite(); //启动可写事件
}

void HandleWrite(Channel* channel)
{
    int fd = channel->Fd();
    const char* data = "来啦～";
    int ret = send(fd, data, strlen(data), 0);
    if(ret < 0)
        return HandleClose(channel); //关闭释放
    channel->DisableWrite(); // 关闭写监控
}

void HandleError(Channel* channel)
{
    return HandleClose(channel);
}


void HandleEvent(EventLoop* loop, Channel* channel, uint64_t timerid)
{
    loop->TimerRefresh(timerid);
    std::cout << "有一个事件\n" << std::endl;
}

void Accpetor(EventLoop* loop, Channel* lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL); 
    if(newfd < 0) { return; }

    uint64_t timerid = rand() % 10000;
    // 为新连接创建一个channel并且添加监控
    Channel* channel = new Channel(loop, newfd);
    channel->SetReadCallBack(std::bind(HandleRead, channel)); // 为通信套接字设置可读事件的回调函数
    channel->SetWriteCallBack(std::bind(HandleWrite, channel)); // 可写事件的回调函数
    channel->SetCloseCallBack(std::bind(HandleClose, channel)); // 关闭事件的回调函数
    channel->SetEventCallBack(std::bind(HandleEvent, loop, channel, timerid)); // 任意事件的回调函数
    channel->EnableRead();

    // 非活跃连接的超时释放操作，10s后关闭连接
    // 注意：定时销毁任务，必须在启动读事件之前，因为有可能启动了事件监控之后，立即就有了事件，但是这时候还没有任务
    loop->TimerAdd(timerid, 10, std::bind(HandleClose, channel));
    channel->EnableRead();
}

int main()
{
    srand(time(nullptr));
    EventLoop loop;
    Socket listen_sock;
    listen_sock.CreateServer(6666);
    // 为监听套接字，创建一个channel进行事件管理，以及事件的处理
    Channel channel(&loop, listen_sock.Fd());
    channel.SetReadCallBack(std::bind(Accpetor, &loop, &channel));
    channel.EnableRead();
    // while (1)
    // {
    //     int newfd = listen_sock.Accept();
    //     if(newfd < 0) continue;
    //     Socket cli_sock(newfd);
    //     char buff[1024] = { 0 };
    //     int ret = cli_sock.Recv(buff, 1023);
    //     if(ret < 0){
    //         cli_sock.Close();
    //         continue;
    //     }
    //     cli_sock.Send(buff, ret);
    //     cli_sock.Close();
    //     std::vector<Channel*> actives;
    //     // loop.Poll(&actives);
    //     for(auto& a : actives)
    //     {
    //         a->HandleEvent();
    //     }
    // }

    while(1)
    {
        loop.Start();
    }

    listen_sock.Close();
    
    return 0;
}